﻿using FluentValidation.Results;
using JSONDB.Model;
using JSONDB.Validation;
using JsonFlatFileDataStore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace JSONDB.helpers
{
    
    public class JsonSave<T> where T : class
    {
        private string path  ;
        
        private DataStore store;

        IDocumentCollection<T> collection  ;

        public JsonSave(string path, string prop = "config") {
            this.path = path;
            this.store = new DataStore(path);
            this.collection = store.GetCollection<T>(prop);
        }

        public void  Save(T item )
        {
         
            collection.InsertOne(item); 
        }

        public List<T> GetItems()
        {
          return  collection.AsQueryable().ToList();
        }

        public async Task UpdateFileCheckSum(string md5)
        {
            bool isSucessful = await store.UpdateItemAsync("checksum", md5);
            if (!isSucessful)
            {
                await store.InsertItemAsync("checksum", md5);

            }
        }

        public string GetFileCheckSum()
        {
            return store.GetItem(Constant.JSONFIELD_CHECKSUM_NAME);
        }

        public async Task ConfigSaveOrUpdate(Tag item)
        {

            var collection = store.GetCollection<Tag>("config");
            bool isSucessful = await collection.UpdateOneAsync((Predicate<Tag>)(t => t.name.Equals(item.name)), item);
            if (!isSucessful)
            {
                await collection.InsertOneAsync(item);
            }
        }

    }
}
